package com.zdp.seckill.common.utils;

import cn.hutool.core.util.StrUtil;
import com.zdp.seckill.common.constant.ApiConstant;
import com.zdp.seckill.common.enums.EmBusinessError;
import com.zdp.seckill.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;


/**
 * 断言工具类
 */
public class AssertUtil {

    /**
     * 必须登录
     *
     * @param accessToken
     */
    public static void mustLogin(String accessToken) {
        if (StrUtil.isBlank(accessToken)) {
            throw new BusinessException(ApiConstant.NO_LOGIN_CODE, ApiConstant.NO_LOGIN_MESSAGE);
        }
    }

    /**
     * 判断字符串非空
     *
     * @param str
     * @param message
     */
    public static void isNotEmpty(String str, String... message) {
        if (StrUtil.isBlank(str)) {
            execute(message);
        }
    }

    /**
     * 判断对象非空
     *
     * @param obj
     * @param message
     */
    public static void isNotNull(Object obj, String... message) {
        if (!Optional.ofNullable(obj).isPresent()) {
            execute(message);
        }
    }

    public static void isNotNull(Object obj, EmBusinessError emBusinessError) {
        if (!Optional.ofNullable(obj).isPresent()) {
            execute(emBusinessError);
        }
    }


    /**
     * 判断结果是否为真
     *
     * @param isTrue
     * @param message
     */
    public static void isTrue(boolean isTrue, String... message) {
        if (isTrue) {
            execute(message);
        }
    }

    /**
     * 判断两个string内容是否相同
     * @param str1
     * @param str2
     */
    public static void strEquals(String str1, String str2, String message) {
       if (StringUtils.isBlank(str1) || StringUtils.isBlank(str2)) {
           execute("参数为空");
       }
       if (!str1.equalsIgnoreCase(str2)) {
           execute(message);
       }
    }

    /**
     * 最终执行方法
     *
     * @param message
     */
    private static void execute(String... message) {
        String msg = ApiConstant.ERROR_MESSAGE;
        if (message != null && message.length > 0) {
            msg = message[0];
        }
        throw new BusinessException(msg);
    }

    /**
     * 根据错误枚举返回异常
     * @param emBusinessError
     */
    private static void execute(EmBusinessError emBusinessError) {
        throw new BusinessException(emBusinessError);
    }

}